/**
 * 用于存储和用户信息相关的API事件和调用，例如:
 * 1. 登录请求，登录成功: 保存用户账号密码和token至本地存储; 登录失败: 删除账号密码和token信息;
 */

import {
  getToken,
  setToken,
  removeToken,
  getAccount,
  setAccount,
  removeAccount,
  setUserId,
  getUserId,
  removeUserId,
} from "@/utils/auth";
import { SUCCESS, FAIL } from "@/utils/constant"; // 返回状态码
import { getUserInfo, getAimUserInfo, emailLogin, login } from "@/api";

const USER = "aimUserInfo";

const state = {
  token: getToken(),
  account: getAccount(), // 存储账号信息，用于自动登录
  [USER]: {}, // 进入个人中心对象的信息
  userInfo: {}, // 自己的个人信息
};

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token;
  },
  SET_ACCOUNT: (state, accountInfo) => {
    state.account = accountInfo;
  },
  SET_USERINFO: (state, userInfo) => {
    state.userInfo = userInfo;
  },
  [USER](state, value) {
    state[USER] = value;
  },
};

const actions = {
  // 进入个人中心对象的信息
  [USER]({ commit }, id) {
    return new Promise((resolve, reject) => {
      getAimUserInfo(id)
        .then((res) => {
          if (res.code === SUCCESS) {
            commit(USER, res.data);
            return resolve();
          }
          reject("获取目标用户信息失败");
        })
        .catch(() => {
          return reject("获取目标用户信息失败");
        });
    });
  },
  Login({ dispatch, commit }, accountInfo) {
    return new Promise((resolve, reject) => {
      let loginType = accountInfo.loginType;
      delete accountInfo.loginType;
      (loginType === "email" ? emailLogin(accountInfo) : login(accountInfo))
        .then((res) => {
          // 登录成功，保存token和用户信息
          if (res.code === SUCCESS) {
            let {
              data: { token, user_id },
            } = res;
            setToken(token);
            commit("SET_TOKEN", token);
            accountInfo.loginType = loginType;
            setAccount(accountInfo);
            commit("SET_ACCOUNT", accountInfo);
            setUserId(user_id);
            // 获取个人资料
            dispatch("updateUserInfo")
              .then((res) => {
                resolve(res);
              })
              .catch(() => {
                resolve();
              });
          } else if (res.code === FAIL) {
            // 登录失败，删除保存的token和用户信息
            dispatch("DeleteInfo");
          }
        })
        .catch((error) => {
          reject(error);
        });
    });
  },
  // 更新新的token
  updateToken({ commit }) {
    commit("getToken");
  },
  // 更新新的用户信息
  updateUserInfo({ commit }) {
    return new Promise((resolve, reject) => {
      // 为空不进行发送
      if (!getUserId()) return;
      getUserInfo(getUserId())
        .then((res) => {
          if (res.code === SUCCESS) {
            commit("SET_USERINFO", res.data);
          } else if (res.code === FAIL) {
            commit("SET_USERINFO", {});
          }
          resolve(res);
        })
        .catch((error) => {
          reject(error);
        });
    });
  },
  // 删除保存的所有用户信息
  DeleteInfo({ commit }) {
    removeToken();
    commit("SET_TOKEN", "");
    removeAccount();
    commit("SET_ACCOUNT", {});
    commit("SET_USERINFO", {});
    removeUserId();
    return Promise.resolve();
  },
  // 自动登录调用接口
  AutoLogin({ dispatch }) {
    return new Promise((resolve, reject) => {
      dispatch("Login", getAccount())
        .then(() => {
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  },
  // 退出登录
  Logout({ dispatch }) {
    return new Promise((resolve, _) => {
      dispatch("DeleteInfo").then(() => {
        resolve();
      });
    });
  },
};

export default {
  namespaced: true,
  actions,
  mutations,
  state,
};
